import { streamCompletion, generateId, getOpenAIKey } from "./functions.js"
import { DEBUG, MODERATION } from "./config.js";
import { Configuration, OpenAIApi } from "openai";
import axios from "axios";

export async function requestCompletionsStream( data ){
    let orgId = generateId();
    let key = getOpenAIKey();

    if( !data.prompt ){
        return {
            status: false,
            error: 'prompt is empty'
        }
    }
    if (DEBUG) console.log(`[Text] [MAX-TOKENS:${data.max_tokens ?? "unset"}] ${data.prompt}`);
    if (MODERATION) {
        try {
            let openAi = new OpenAIApi(new Configuration({ apiKey: key , basePath: "http://148.72.244.174:9000/v1"}));
            let response = await openAi.createModeration({
                input: data.prompt,
            });

            if (response.data.results[0].flagged) {
                return {
                    status: false,
                    error: "Your prompt contains content that is not allowed",
                    reason: response.data.results[0].reason
                };
            }
        }
        catch (e) {
            return {
                status: false,
                error: e && e.message
            }
        }
    }

    try{
        const response = await axios.post(
            `http://148.72.244.174:9000/v1/completions`, 
            data,
            {
                responseType: "stream",
                headers: {
                    Accept: "text/event-stream",
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${key}`,
                },
            },
        );
        return {
            status: true,
            response: response
        }
    } catch (error) {
        try {
            if (error.response && error.response.data) {
                let errorResponseStr = "";
                for await (const message of error.response.data) {
                    errorResponseStr += message;
                }
                errorResponseStr = errorResponseStr.replace(/org-[a-zA-Z0-9]+/, orgId);
                const errorResponseJson = JSON.parse(errorResponseStr);
                return {
                    status: false,
                    error: errorResponseJson
                };
            } else {
                if (DEBUG) console.error("Could not JSON parse stream message", error);
                return {
                    status: false,
                    error: "something went wrong1!"
                };
            }
        }
        catch (e) {
            console.log(e);
            return {
                status: false,
                error: "something went wrong2!"
            };
        }
    }

}

export async function requestChatCompletionsStream( data ){
    let orgId = generateId();
    let key = getOpenAIKey();

    if( !data.messages ){
        return {
            status: false,
            error: 'prompt is empty'
        }
    }
    if (DEBUG) console.log(`[Text] [MAX-TOKENS:${data.max_tokens ?? "unset"}] ${data.prompt || data.messages}`);
    
    try{
        const response = await axios.post(
            `http://148.72.244.174:9000/v1/chat/completions`, 
            data,
            {
                responseType: "stream",
                headers: {
                    Accept: "text/event-stream",
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${key}`,
                },
            },
        );
        return {
            status: true,
            response: response
        }
    } catch (error) {
        try {
            if (error.response && error.response.data) {
                let errorResponseStr = "";
                for await (const message of error.response.data) {
                    errorResponseStr += message;
                }
                errorResponseStr = errorResponseStr.replace(/org-[a-zA-Z0-9]+/, orgId);
                const errorResponseJson = JSON.parse(errorResponseStr);
                return {
                    status: false,
                    error: errorResponseJson
                };
            } else {
                if (DEBUG) console.error("Could not JSON parse stream message", error);
                return {
                    status: false,
                    error: "something went wrong1!"
                };
            }
        }
        catch (e) {
            console.log(e);
            return {
                status: false,
                error: "something went wrong2!"
            };
        }
    }
}


// const controller = new AbortController();
// const response = await fetchEventSource('http://43.134.126.123/v1/completions', {
//     method: 'POST',
//     headers: {
//         // "Accept": "text/event-stream",
//         "Content-Type": "application/json",
//         "Authorization": `Bearer ${key}`,
//     },
//     body: JSON.stringify(req),
//     signal: controller.signal,
//     onopen(response) {
//         if (response.status === 200) {
//             return;
//         }
//         throw new Error(`Failed to send message. HTTP ${response.status} - ${response.statusText}`);
//     },
//     onclose() {
//         throw new Error('Failed to send message. Server closed the connection unexpectedly.');
//     },
//     onerror(err) {
//         throw err;
//     },
//     onmessage(message) {
//         console.log(message)
//     }
// })
// const response = await axios.post(
//     `https://service-qkkr4pqt-1253830318.ca.tencentapigw.com/v1/completions`, req,
//     {
//         // proxy: {
//         //     protocol: 'http',
//         //     host: '127.0.0.1',
//         //     port: 3213,
//         // },
//         headers: {
//             // Accept: "text/event-stream",
//             "Content-Type": "application/json",
//             Authorization: `Bearer ${key}`,
//         },
//     },
// );
// console.log(response);
// return response;